import { computed, ref } from 'vue';
import { InputNumber } from 'ant-design-vue';
import { inputValueToInt } from '@/util/index.js';
import { read } from 'xlsx/xlsx.mjs';
import { Pairs } from '@/util/xls.js';

export function useQuesAssign({ dataSource, fileList, fileTotal, countUploaded, uploadFailedList }) {
  const quesNumToInt = R.compose( Number.parseInt, R.prop('fileNum') );
  const sumQuesNum = R.compose( R.sum, R.map(quesNumToInt) );
  const sumAssignableStartAt = computed(() => R.compose( R.subtract(fileTotal.value), sumQuesNum, R.slice(0, R.__, dataSource.value) ));
  const isAssignedForAll = computed(() => R.all( R.compose( R.gt(R.__, 0), quesNumToInt ), dataSource.value ));
  const quesNumMaxList = computed(() => R.compose( R.map(sumAssignableStartAt.value), R.keys )(dataSource.value));

  async function handleChangeXls(event) {
    const elem = event.currentTarget;
    
    // Rownum[] -> [[A1.v, B2.v]] -> fromPairs
    const dic = await new Promise(resolve => {
      const fr = new FileReader();
      fr.readAsArrayBuffer(elem.files[0]);
      fr.addEventListener('load', 
        R.compose(
          resolve,
          R.fromPairs,
          Pairs,
          R.path(['Sheets', 'Sheet1']),
          read,
          R.path(['target', 'result'])
        )
      );
    });
  
    R.compose(
      R.forEach(o => ( o.fileNum = dic[o.realName] )),
      R.filter(R.compose( R.has(R.__, dic), R.prop('realName') ))
    )(dataSource.value)
    
    elem.value = '';
  }

  const columns = ref([
    {
      title: '标注人员',
      dataIndex: 'realName',
    },
    {
      width: '9em',
      title: '题数',
      dataIndex: 'fileNum',
      customRender: ({ record, text, index }) => (
        <InputNumber
          value={text}
          disabled={!(fileList.value.length == countUploaded.value && uploadFailedList.value.length < countUploaded.value)}
          controls={false}
          min={0}
          max={quesNumMaxList.value[index]}
          step={1}
          onBlur={event => {
            record.fileNum = R.compose( R.clamp(0, quesNumMaxList.value[index]), inputValueToInt )(event);
            const assignableTotal = sumAssignableStartAt.value(index + 1);
            const restRows = dataSource.value.slice(index + 1);
    
            restRows.forEach( o => (o.fileNum = Math.floor(assignableTotal / restRows.length)) );
    
            restRows
            .slice(0, assignableTotal % restRows.length)
            .forEach(o => o.fileNum = quesNumToInt(o) + 1);
          }}
        >
        </InputNumber>
      ),
    },
  ]);
  
  return {
    handleChangeXls,
    columns,
    isAssignedForAll,
  };
}
